/**
 * jQuery for module textbooks - controller book
 * 
 * @author	huytbt
 * @date	2012-05-07
 * @version	1.0
 */

;if(window.jQuery) (function($){
	if (!jQuery.h) jQuery.extend({h:{}}); // declare alias $.h
	if (!jQuery.h.textbooks) jQuery.h.textbooks = {}; // declare alias $.h.textbooks
	jQuery.h.textbooks.book = {
		/**
		 * Class GoogleBooksAPI - used to process post book
		 */
		GoogleBooksAPI: {
			search: function(query, callback) {
				jQuery.ajax({
					dataType: 'json',
					url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + escape(query),
					success: function(response) {
						if (callback) callback(response);
					}
				});
				return;
				
				// Ex: query = 0596000278,00-invalid-isbn,ISBN0765304368,0439554934
				// Delete any previous Google Booksearch JSON queries.
				var jsonScript = document.getElementById("jsonScript");
				if (jsonScript) {
					jsonScript.parentNode.removeChild(jsonScript);
				}

				// Add a script element with the src as the user's Google Booksearch query.
				// JSON output is specified by including the alt=json-in-script argument
				// and the callback funtion is also specified as a URI argument.
				var scriptElement = document.createElement("script");
				scriptElement.setAttribute("id", "jsonScript");
				scriptElement.setAttribute("src",
					"http://books.google.com/books?bibkeys=" +
					escape(query) + "&jscmd=viewapi&callback="+callback);
				scriptElement.setAttribute("type", "text/javascript");
				// make the request to Google booksearch
				document.documentElement.firstChild.appendChild(scriptElement);
			}
		},
		/**
		 * Method syncThumbnailBook - not performance
		 */
		syncThumbnailBook: function(response) {
			jQuery.each(response.items, function(index, item) {
				if (item.volumeInfo.imageLinks) {
					$('input#TextbookBook_thumbnail').val(item.volumeInfo.imageLinks.thumbnail);
					$('.h-textbooks-book-thumbnail img').attr('src', item.volumeInfo.imageLinks.thumbnail);
					$('.h-textbooks-book-thumbnail').fadeIn();
				}
				if (item.volumeInfo.title) $('input#TextbookBook_title').val(item.volumeInfo.title);
				if (item.volumeInfo.authors) $('input#TextbookBook_author').val(item.volumeInfo.authors.join(', '));
				// if (item.volumeInfo.description) $('textarea#TextbookBook_description').val(item.volumeInfo.description);
			});
			$('input#TextbookBook_google_api_json').val(jQuery.toJSON(response));
		},
		/**
		 * Class FormPostBook - used to process post book
		 */
		FormPostBook: function(element)
		{
			var _this = this;
			_this.instance = $(element);
			
			_this.initForm = function(){
				_this.instance.find('.h-textbooks-books-link-search-isbn').click(function(){
					var department = _this.instance.find('select#TextbookBook_department_id').val();
					if (department == 0) {
						$('#TextbookBook_department_id_em_').hide().html('Please select a department.').fadeIn();
						return false;
					}
					$('.errorMessage').hide();
					var isbn = _this.instance.find('input#TextbookBook_isbn').val();
					if (isbn) {
						jQuery.h.textbooks.book.GoogleBooksAPI.search(isbn, jQuery.h.textbooks.book.syncThumbnailBook);
					}
					_this.instance.find('.h-textbooks-div-hidden').fadeIn();
					_this.instance.find('.h-textbooks-books-link-search-isbn').hide();
					_this.instance.find(':submit').removeAttr("disabled").fadeIn();
					return false;
				});
				
				_this.instance.submit(function(){
					return true;
					_this.instance.find(':submit').attr("disabled", "true");
					_this.instance.find('.errorMessage').fadeOut();
					$.ajax({
						dataType: 'JSON',
						type: _this.instance.attr('method'),
						data: _this.instance.serialize(),
						url: _this.instance.attr('action'),
						success: function(response) {
							_this.instance.find(':submit').removeAttr("disabled");
							if (response.error) {
								$.each(response.data, function(key, value){
									var html = value.join('<br/>');
									_this.instance.find('.errorMessage.errorField_'+key).html(html).fadeIn();
								});
							} else
								window.location = response.data.redirectUrl;
						}
					});
					
					return false;
				});
				
				return _this;
			};
		}
	};
})(jQuery);

;if(window.jQuery) (function($){
	$(document).ready(function(){
		$('select#course_id').change(function(){
			$(this).parent().submit();
		});
		
		$('form.h-textbooks-form-post-book').each(function(){
			var $postBook = new jQuery.h.textbooks.book.FormPostBook(this);
			$postBook.initForm();
		});
	});
})(jQuery);